package com.alpha.service.utils;

import com.google.errorprone.annotations.CanIgnoreReturnValue;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.data.redis.core.script.DefaultRedisScript;
import org.springframework.data.redis.core.script.RedisScript;
import org.springframework.stereotype.Component;

import java.util.Collections;
import java.util.concurrent.TimeUnit;

/**
 * Redis 工具类
 *
 * @author chenruwan
 * @since 2021-12-31
 */
@Slf4j
@Component
public class RedisUtil {
    public static final int DEFAULT_LOCK_EXPIRE_TIME = 10;
    public static final int DEFAULT_LOCK_RETRY_TIME = 3;
    private static final Long RELEASE_SUCCESS = 1L;
    private static final String RELEASE_SCRIPT = "if redis.call('get', KEYS[1]) == ARGV[1] " +
            "then return redis.call('del', KEYS[1]) " +
            "else return 0 end";

    private static RedisTemplate<String, String> redisTemplate;

    @Autowired
    private RedisUtil(RedisTemplate<String, String> redisTemplate) {
        RedisUtil.setRedisTemplate(redisTemplate);
    }

    private static void setRedisTemplate(RedisTemplate<String, String> redisTemplate) {
        RedisUtil.redisTemplate = redisTemplate;
    }

    /**
     * 尝试获取分布式锁
     *
     * @param key        锁
     * @param owner      身份标识
     * @param expireTime 过期时间(sec)
     * @param retryTime  重试次数(一次一秒)
     * @return 是否获取成功
     */
    public static boolean tryLock(String key, String owner, int expireTime, int retryTime) {
        do {
            if (tryLock(key, owner, expireTime)) {
                return true;
            }

            try {
                if (retryTime > 0) {
                    Thread.sleep(1000);
                }
            } catch (InterruptedException e) {
                log.warn("Caught Exception : ", e);
                Thread.currentThread().interrupt();
            }
        } while (retryTime-- > 0);

        return false;
    }

    public static boolean tryLock(String key, String owner, int expireTime) {
        Boolean result = redisTemplate.opsForValue().setIfAbsent(key, owner, expireTime, TimeUnit.SECONDS);
        return Boolean.TRUE.equals(result);
    }

    /**
     * 释放分布式锁
     *
     * @param key   锁
     * @param owner 身份标识
     * @return 是否释放成功
     */
    @CanIgnoreReturnValue
    public static boolean unlock(String key, String owner) {
        RedisScript<Long> redisScript = new DefaultRedisScript<>(RELEASE_SCRIPT, Long.class);

        Long result = redisTemplate.execute(redisScript, Collections.singletonList(key), owner);
        if (!RELEASE_SUCCESS.equals(result)) {
            log.warn("释放锁失败，过期后自动释放，key = {}, owner = {}", key, owner);
            return false;
        }

        return true;
    }
}
